package fourfaith.com.ff_sl21_app;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.util.HashMap;
import java.util.Map;

import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.LoadingDialog;
import fourfaith.com.ff_sl21_app.utils.RequestQueueSingleton;
import fourfaith.com.ff_sl21_app.utils.ResponseResult;

public class LoginActivity extends AppCompatActivity {

    private CheckBox checkBox;
    private EditText userName;
    private EditText userPwd;
    private Dialog dialog;
    private JsonRequest<ResponseResult> jsonRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();
        SharedPreferences sharedPreferences = getSharedPreferences(Constants._loginInfo, Context.MODE_PRIVATE);
        boolean isCheck = sharedPreferences.getBoolean("remberPwd",false);
        if(isCheck){
            checkBox.setChecked(isCheck);
            userName.setText(sharedPreferences.getString("userName",""));
            userPwd.setText(sharedPreferences.getString("userPwd", ""));
        }

    }

    private  void initView() {
        userName = (EditText) findViewById(R.id.userName);
        userPwd = (EditText) findViewById(R.id.userPwd);
        checkBox = (CheckBox) findViewById(R.id.checkBox);
        ImageButton loginButton = (ImageButton) findViewById(R.id.loginButton);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String _username = userName.getText().toString();
                String _password = userPwd.getText().toString();
                if (valid(_username, _password)) {
                    boolean _checkBox = checkBox.isChecked();
                    getLoginRequest(_username, _password, _checkBox);
                }
            }
        });
    }

    private boolean valid(String username, String password) {

        if(!Constants.isNotEmpty(username)){
            Toast.makeText(LoginActivity.this, getString(R.string.prompt_username) +"不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if(!Constants.isNotEmpty(password)){
            Toast.makeText(LoginActivity.this, getString(R.string.prompt_password) +"不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void getLoginRequest(final String username,final String password,final boolean _checkBox) {

        RequestQueue mQueue = RequestQueueSingleton.getInstance(this).getRequestQueue();

        Map<String, String> params = new HashMap<>();
        params.put("userName",username);
        params.put("userPwd",password);

        dialog = new LoadingDialog(LoginActivity.this).setMessage("正在登录...");
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                jsonRequest.cancel();
                dialog.dismiss();
            }
        });
        dialog.show();

        jsonRequest = new JsonRequest<>(Request.Method.POST, Constants.login, ResponseResult.class,
                new Response.Listener<ResponseResult>() {
                    @Override
                    public void onResponse(ResponseResult obj) {
                        if (obj.getCode().equals("200")) {
                            saveInfo(obj);

//                            Toast.makeText(LoginActivity.this, "登录请求成功...", Toast.LENGTH_SHORT).show();

                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        } else {
                            Toast.makeText(LoginActivity.this, obj.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                        if (dialog.isShowing() && dialog != null) {
                            dialog.dismiss();
                        }
                    }
                    /**
                     * 保存信息
                     *
                     * @param obj
                     */
                    private void
                    saveInfo(ResponseResult obj) {
                        Object objData = obj.getData();//获取用户的数据
                        String userId = "";
                        try {
                            JSONObject result = (JSONObject) JSON.toJSON(objData);//转换为JSONObject
                            userId = result.getString("id");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        SharedPreferences sharedPreferences = getSharedPreferences(Constants._loginInfo, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                        editor.putString("userId",userId);
                        editor.putString("userName", username);
                        if (_checkBox) {
                            editor.putString("userPwd", password);
                            editor.putBoolean("remberPwd", _checkBox);

                        } else {
                            editor.remove("remberPwd");
                            editor.remove("userPwd");
                        }
                        editor.commit();
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (dialog.isShowing() && dialog != null) {
                    dialog.dismiss();
                }
                if (error.networkResponse == null) {
                    Toast.makeText(LoginActivity.this, "连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
                } else {
                    if (error.getMessage() == null) {
                        Toast.makeText(LoginActivity.this, "接口服务器异常", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(LoginActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

            }

        },params);
        mQueue.add(jsonRequest);
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                // 关闭应用程序
                // 返回桌面操作
                Intent home = new Intent(Intent.ACTION_MAIN);
                home.addCategory(Intent.CATEGORY_HOME);
                startActivity(home);
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
